#include <cstdio>
#include <queue>

int n;
long long ans;
std::priority_queue<int, std::vector<int>, std::greater<int> > pq;

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("testdata.in", "r", stdin);
  freopen("testdata.out", "w", stdout);
#else
  freopen("CF865D Buy Low Sell High.in", "r", stdin);
  freopen("CF865D Buy Low Sell High.out", "w", stdout);
#endif
#endif

  scanf("%d", &n);
  for (int i = 1, a; i <= n; ++i) {
    scanf("%d", &a);
    if (!pq.empty() && pq.top() < a) {
      ans += a - pq.top();
      pq.pop();
      pq.push(a);
    }
    pq.push(a);
  }
  printf("%lld", ans);
  return 0;
}